﻿using DingChiServiceApp.db;
using DingChiServiceApp.entity;
using DingChiServiceApp.helper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Security.Permissions;
using System.Security.Policy;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace DingChiServiceApp.service
{
    public partial class DingChiService : ServiceBase
    {
        #region Timer
        private Timer mTimer;
        #endregion

        #region property
        private DuplicateDao _dao;
        private DuplicateDao Dao
        {
            get
            {
                if (_dao == null)
                {
                    _dao = new DuplicateDao();
                }
                return _dao;
            }
        }

        #endregion

        public DingChiService()
        {
            InitializeComponent();
            InitTimer();
        }

        private void InitTimer()
        {
            LocalConfig localconfig = LocalConfigJsonDao.Instance.GetLocalConfig();
            if (localconfig.interval <= 0) localconfig.interval = 10 * 1000;
            mTimer = new Timer()
            {
                Interval = localconfig.interval * 1000,
            };
            mTimer.BeginInit();
            mTimer.Elapsed += MTimer_Elapsed;
            mTimer.EndInit();
        }

        private void MTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            StartDataSync();
        }


        //开始 同步数据
        private void StartDataSync()
        {
             //开始同步数据
            try
            {
                DataSyncHelper.Up();
            }
            catch (Exception ex)
            {
                var msg = "上传数据错误：" + ex.Message + "\r\n" + ex.StackTrace;
                LogHelper.FileLog(msg);
            }
            System.Threading.Thread.Sleep(1000);
            try
            {
                DataSyncHelper.RepetitionUp();
            }
            catch (Exception ex)
            {
                var msg = "上传修改后的数据错误：" + ex.Message+"\r\n"+ex.StackTrace;
                LogHelper.FileLog(msg);
            }
        }

        protected override void OnStart(string[] args)
        {
            new Task(() =>
            {
                LogHelper.FileLog(" ---------- DingChiService OnStart");
                mTimer?.Start();
            }).Start();

        }

        protected override void OnStop()
        {
            base.OnStop();
            LogHelper.FileLog(" ---------- DingChiService OnStop");
            mTimer?.Stop();
        }

        protected override void OnShutdown()
        {
            mTimer?.Dispose();
            mTimer = null;
            base.OnShutdown();
        }
    }
}
